package com.apes.framework.jpa.logger;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.ReflectUtil;
import com.apes.oap.RopRequestContext;
import com.apes.oap.session.RopSessionHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能：Logger 服务
 *
 * @author xul
 * @create 2018-03-13 19:13
 */
@Service
public class ApesLoggerService extends DomainService {


    @Autowired
    ApesLoggerRepository repository;


    /**
     * 功能：创建ApesLogger
     */
    public ApesLogger save(SimpleRequest request) {
        ApesLogger logger = request.getO(ApesLogger.class);
        return repository.saveAndFlush(logger);
    }

    public List<ApesLogger> find(SimpleRequest request) {
        List<ApesLogger> loggers = repository.findAllByBusinessKeyAndAndBusinessTypeOrderByBusinessDateDesc(request.get("businessKey"), request.get("businessType"));
        loggers.stream().forEach(logger -> {
            logger.setOperator(getOperator(logger.getOperator_id(), logger.getOperatorName()));
        });
        return loggers;
    }


    /**
     * 寻找审核日志
     * @param request
     * @return
     */
    public List<ApesLogger> findAudit(SimpleRequest request) {
        List<ApesLogger> loggers = repository.findAllByBusinessKeyAndBusinessTypeAndOaFlagAndRemarkIsNotNullOrderByCreateDateAsc(request.get("businessKey"), request.get("businessType"),Boolean.TRUE);
        if (loggers.size()==0) return loggers;
        loggers.stream().forEach(logger -> {
            logger.setOperator(getOperator(logger.getOperator_id(), logger.getOperatorName()));
        });
        return filterAudit(loggers,request.get("audit"));
    }

    /**
     * 过滤技术审核或者价格审核
     * @param loggers
     * @param audit 保留的审核类型
     * @return
     */
    public List<ApesLogger> filterAudit(List<ApesLogger> loggers,String audit){
        List<ApesLogger> auditLogger = loggers;
        if ("tech".equals(audit)){
            auditLogger = loggers.stream().filter(apesLogger -> apesLogger.getOperate().split("：")[0].contains("审批")).collect(Collectors.toList());
        }
        if ("price".equals(audit)){
            auditLogger = loggers.stream().filter(apesLogger -> !apesLogger.getOperate().split("：")[0].contains("审批")&&!apesLogger.getRemark().contains("[转签]")).collect(Collectors.toList());
        }
        if (auditLogger.size()>10){
            for (int i = 0; i <auditLogger.size()-10; i++) {
                auditLogger.remove(0);
            }
        }
        return auditLogger;
    }

    @Listener(topic = "event:ir.logger.create")
    public void onMessage(SimpleRequest request) {
        ApesLogger logger = request.getO(ApesLogger.class);
        Map m = request.getMap();
        if (!m.containsKey("operator_id") || StringUtils.isEmpty(m.get("operator_id"))) {
            Object user = getCurrentUser(request);
            if (user != null) {
                Integer userId = ReflectUtil.getFieldValue(user, "id");
                logger.setOperator_id(userId);
            }
        }
        if (StringUtils.isEmpty(logger.getWorkPostName())) {
            SimpleSession session = getSession(request);
            if (session != null) {
                logger.setWorkPostName(session.getAttribute("workPostName", String.class));
            }
        }
        logger.setBusinessDate(new Date());
        repository.saveAndFlush(logger);
    }

    @Listener(topic = "event:ir.logger.save")
    public void saveLogger(SimpleRequest request) {
        ApesLogger logger = request.getO(ApesLogger.class);
        Map m = request.getMap();
        if (!m.containsKey("operator_id") || StringUtils.isEmpty(m.get("operator_id"))) {
            Object user = getCurrentUser(request);
            if (user != null) {
                Integer userId = ReflectUtil.getFieldValue(user, "id");
                logger.setOperator_id(userId);
            }
        }
        logger.setBusinessDate(new Date());
        repository.saveAndFlush(logger);
    }

    /**
     * 添加日志
     *
     * @param request
     * @return
     */
    public ApesLogger add(SimpleRequest request) {
        SimpleSession session = request.getSession();
        JSONObject jo = request.getJO();
        ApesLogger logger = new ApesLogger();
        if (session!=null){
            Integer userId = Integer.valueOf(session.getUserId());
            Map operator = getOperator(userId, "");
            logger.setOperator(operator);
            logger.setOperator_id(userId);
            logger.setWorkPostName(session.getAttribute("workPostName", String.class));
        }
        if (jo.containsKey("operator_id")) logger.setOperator_id(jo.getInteger("operator_id"));
        if (jo.containsKey("operatorName")) logger.setOperatorName(jo.getString("operatorName"));
        logger.setBusinessDate(new Date());
        logger.setBusinessKey(request.get("businessKey"));
        logger.setBusinessType(request.get("businessType"));
        logger.setOperate(request.get("operate"));
        logger.setOaFlag(request.get("oaFlag"));
        logger.setRemark(request.get("remark"));
        return repository.saveAndFlush(logger);
    }

    private Map getOperator(Integer operatorId, String operatorName) {
        if (operatorId == null) return new HashMap();
        if (StringUtils.hasText(operatorName)) {
            return MapUtil.mapper("id", operatorId, "name", operatorName);
        }
        Object result = getUser(operatorId);
        return MapUtil.mapper("id", operatorId, "name", result != null ? ReflectUtil.getFieldValue(result, "name") : operatorName);
    }

}
